package com.hinnotek.warehouse.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.hinnotek.warehouse.api.WarehouseApi
import com.hinnotek.warehouse.utils.StringUtils
import com.lee.common.network.getRequestBody
import com.lee.common.utils.PAGE_SIZE
import com.lee.common.utils.SharedPreUtils
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject


/**
 * 入库
 */
@HiltViewModel
class StockInViewModel @Inject constructor() :
    BaseViewModel() {

    var applyNum = ""
    var applyId = 0
    var applyDeviceId = 0
    var applyType = "01"
    var goodsType = "01"
    var approvalUserId = 1

    //是否通过
    var approvalState = 0

    //拒绝理由
    var refusalReasons = ""
    var approvalApplyId = 0


    fun setParameters(applyNum: String) {
        this.applyNum = applyNum
    }

    fun setParameters(applyId: Int?) {
        this.applyId = applyId ?: 0
    }


    val complete = MutableLiveData<Boolean>()
    val clickComplete = MutableLiveData<Boolean>()


    fun isComplete() {
        complete.value = true
    }

    fun toClickComplete() {
        loading.value = true
        clickComplete.value = true
    }

    override fun loadData() {
        refreshTrigger.value = true
        loading.value = true
    }


    private val stockIn = Transformations.switchMap(page) {
        val map = mutableMapOf<String, Any>().apply {
            put("applyType", applyType)
            put("approvalUserId", SharedPreUtils.getInteger("userId", 0))
            put("pageNo", it)
            put("pageSize", PAGE_SIZE)
            if (applyNum != "") {
                put("applyNum", applyNum)
            }
        }
        api.getWarehourseApplyFormPage(getRequestBody(map))
    }

    private val stockInDetail = Transformations.switchMap(page) {
        api.getWarehourseApplyFormDetailListByApplyDeviceId(applyDeviceId)
    }

    private val stockInList = Transformations.switchMap(page) {
        api.getWarehourseApplyFormDeviceListByApplyId(applyId)
    }

    private val completeState = Transformations.switchMap(complete) {
        api.completeWarehourseApplyForm(applyId)
    }

    private val clickCompleteState = Transformations.switchMap(clickComplete) {
        api.clickCompleteWarehouseApplyForm(applyId)
    }

    private val approval = Transformations.switchMap(refreshTrigger) {
        val map = mutableMapOf<String, Any>().apply {
            put("applyId", approvalApplyId)
            //同意传2，拒绝传3 int
            put("approvalState", approvalState)
            put("refusalReasons", refusalReasons)
        }
        api.approvalWarehourseApplyForm(getRequestBody(map))
    }

    val stockInPage = mapPage(stockIn)

    val stockInDetailPage = mapPage(stockInDetail)

    val stockInListPage = mapPage(stockInList)

    val approvalData = mapData(approval)

    val isCompleteData = mapData(completeState)

    val clickCompleteData = mapData(clickCompleteState)


}